import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:nl_photo_picker/nl_photo_picker.dart';

void main() => runApp( MyApp());
//将counter对象添加进providers
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
 
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
          title: '优路老师',
          home: MyHomePage(),
        );
  }
  
}


class MyHomePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MyHomeState();
  }
  
}
class MyHomeState extends State<MyHomePage>{

  List<AssetEntity> images = [];
  List<File> imagesFiles = [];

  void _testPhotoListParams() async {
    var assetPathList = await PhotoManager.getImageAsset();
    _pickAsset(PickType.all, pathList: assetPathList);
  }

  void _pickAsset(PickType type, {List<AssetPathEntity> pathList}) async {
    var result = await PhotoManager.requestPermission();
    if(!result)  return;
    List<AssetEntity> tempSelected = [];
    tempSelected.addAll(images);

    List<AssetEntity> imgList = await PhotoPicker.pickAsset(
      // BuildContext required
      context: context,

      /// The following are optional parameters.
      themeColor: Colors.black,
      // the title color and bottom color

      textColor: Colors.white,
      // text color
      padding: 5.0,
      // item padding
      dividerColor: Colors.white,
      // divider color
      disableColor: Colors.grey.shade300,
      // the check box disable color
      itemRadio: 0.88,
      // the content item radio
      maxSelected: 8,
      // max picker image count
      // provider: I18nProvider.english,
      provider: I18nProvider.chinese,
      // i18n provider ,default is chinese. , you can custom I18nProvider or use ENProvider()
      rowCount: 3,
      // item row count

      thumbSize: 150,
      // preview thumb size , default is 64
      sortDelegate: SortDelegate.common,
      // default is common ,or you make custom delegate to sort your gallery
      checkBoxBuilderDelegate: DefaultCheckBoxBuilderDelegate(
        activeColor: Colors.white,
        unselectedColor: Colors.white,
        checkColor: Colors.green,
      ),
      // default is DefaultCheckBoxBuilderDelegate ,or you make custom delegate to create checkbox

      loadingDelegate: Loading(),
      // if you want to build custom loading widget,extends LoadingDelegate, [see example/lib/main.dart]

      badgeDelegate: const DurationBadgeDelegate(),
      // badgeDelegate to show badge widget

      pickType: type,

      photoPathList: pathList,
      selectedList: tempSelected,
      normalIndicatorColor: Colors.green
    );
    print(imgList);
    if (imgList == null || imgList.isEmpty) {

    } else {
      List<File> r = [];

      for (var e in imgList) {
        var file = await e.file;
       r.add(file);
      }
      imagesFiles = r;

      List<AssetEntity> a = [];
      a.addAll(imgList);
      images = a;
    }
    setState(() {});
  }



  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("选择图片"),
      ),
      body:Container(
          child: Column(
            children: <Widget>[
              IconTextButton(
                  icon: Icons.photo,
                  text: "photo",
                  onTap: (){_pickAsset(PickType.onlyImage);}
                  ),
              IconTextButton(
                  icon: Icons.videocam,
                  text: "video",
                  onTap: () {
                    _pickAsset(PickType.onlyVideo);
                  }
              ),
              IconTextButton(
                  icon: Icons.album,
                  text: "all",
                  onTap: (){
                    _pickAsset(PickType.all);
                  }),
              IconTextButton(
                  icon: Icons.camera,
                  text: "平台图库",
                  onTap: (){
                    choosePhotoNative(ImageSource.gallery);
                  }),
              IconTextButton(
                  icon: Icons.party_mode,
                  text: "相机",
                  onTap: (){
                    choosePhotoNative(ImageSource.camera);
                  }),
              Expanded(
                  child: GridView.builder(
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: 10,
                        mainAxisSpacing: 10,
                      ),
                      itemCount: images.length,
                      itemBuilder: (BuildContext context, int index) {
                        //Widget Function(BuildContext context, int index)
                        AssetEntity entity = images[index];
//                        getFile(entity);
                        return Stack(
                          children: <Widget>[
                            RepaintBoundary(
                                child:Container(
                                  child: ImageItem(
                                    entity: entity,
                                    themeColor: Colors.yellow,
                                    size: 150,
                                    loadingDelegate: Loading(),
                                    badgeDelegate: const DurationBadgeDelegate(),
                                  ),
                                )
                            ),
//                            _buildMask(true),
                            _buildSelected(images[index]),
                          ],
                        );
                      }),

                ),
              Expanded(
                child: GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                    ),
                    itemCount: imagesFiles.length,
                    itemBuilder: (BuildContext context, int index) {
                      //Widget Function(BuildContext context, int index)
                      File entityFile = imagesFiles[index];
//                        getFile(entity);
                      return Stack(
                        fit: StackFit.expand,
                        children: <Widget>[
                          Image.file(entityFile,width: 200,height: 200,fit: BoxFit.cover,),
                        ],
                      );
                    }),

              ),
            ],

          ),
      )
    );
  }
  getFile(AssetEntity entity)async{
    File file = await entity.file;
    print(file);
  }
  Widget _buildSelected(AssetEntity entity) {
    var currentSelected = containsEntity(entity);
    return Positioned(
      right: 0.0,
      width: 36.0,
      height: 36.0,
      child: GestureDetector(
        onTap: () {
//          changeCheck(!currentSelected, entity);
        },
        behavior: HitTestBehavior.translucent,
        child: Center(
          child: Text(""),
        ),
      ),
    );
  }
  Widget _buildText(AssetEntity entity,) {
    var isSelected = containsEntity(entity);
    Widget child;
    BoxDecoration decoration;
    if (isSelected) {
      child = Text(
        (1).toString(),
        textAlign: TextAlign.center,
        style: TextStyle(
          fontSize: 12.0,

        ),
      );
      decoration = BoxDecoration(color: Colors.red);
    } else {
      decoration = BoxDecoration(
        borderRadius: BorderRadius.circular(1.0),
        border: Border.all(
          color: Colors.green,
        ),
      );
    }
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        decoration: decoration,
        alignment: Alignment.center,
        child: child,
      ),
    );
  }

  bool containsEntity(AssetEntity entity) {
    return images.contains(entity);
  }
  _buildMask(bool showMask) {
    return IgnorePointer(
      child: AnimatedContainer(
        color: showMask ? Colors.black.withOpacity(0.5) : Colors.transparent,
        duration: Duration(milliseconds: 300),
      ),
    );
  }
  choosePhotoNative(type) async {

    var image = await NlPhotoPicker.pickImage(source: type);
//    if(image == null) return;
//    AssetEntity assetEntity = AssetEntity(id: image);
    if(image == null) return;
    var image2 = await PhotoManager.createAssetEntityWithId(image);
    images.add(image2);
    setState(() {

    });


  }
  Future<AssetEntity> createAssetEntityWithId(String id) {
//    return PhotoManager._createAssetEntityWithId(id);
  }

  
}
class IconTextButton extends StatelessWidget {
  final IconData icon;
  final String text;
  final Function onTap;

  const IconTextButton({Key key, this.icon, this.text, this.onTap})
      : super(key: key);

  @override
  Widget build(BuildContext context){
    return InkWell(
      onTap: onTap,
      child: Container(

        child: ListTile(
          leading: Icon(icon ?? Icons.device_unknown,color: Colors.green,),
          title: Text(text ?? ""),
        ),
      ),
    );
  }
}


class Loading extends LoadingDelegate{
  @override
  Widget buildBigImageLoading(BuildContext context, AssetEntity entity, Color themeColor) {
    // TODO: implement buildBigImageLoading
    return Center(
      child: Container(
        width: 50.0,
        height: 50.0,
        child: CupertinoActivityIndicator(
          radius: 25.0,
        ),
      ),
    );
  }

  @override
  Widget buildPreviewLoading(BuildContext context, AssetEntity entity, Color themeColor) {
    // TODO: implement buildPreviewLoading
    return Center(
      child: Container(
        width: 50.0,
        height: 50.0,
        child: CupertinoActivityIndicator(
          radius: 25.0,
        ),
      ),
    );
  }

}
